package com.jielihaofeng.nettyadvance.rpc.server.service;

import com.jielihaofeng.nettyadvance.rpc.config.Config;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Johnnie Wind
 * @description 服务获取工厂
 * @date 2021/11/19 14:28
 */
@Slf4j
public class ServiceFactory {

    static Properties properties;
    static Map<Class<?>, Object> serviceMap = new ConcurrentHashMap<>();

    // 初始化服务
    static {
        try (InputStream in = Config.class.getResourceAsStream("/application.properties")) {
            properties = new Properties();
            properties.load(in);

            Set<String> propertyNames = properties.stringPropertyNames();
            for (String propertyName : propertyNames) {
                if (propertyName.endsWith("Service")) {
                    Class<?> interfaceClass = Class.forName(propertyName);
                    Class<?> instanceClass = Class.forName(properties.getProperty(propertyName));
                    serviceMap.put(interfaceClass, instanceClass.newInstance());
                }
            }
            log.info("初始化服务：{}", serviceMap);
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * @description 获取服务
     * @author Johnnie Wind
     * @date 2021/11/19 14:43
     */
    public static <T> T getService(Class<T> interfaceClass) {
        return (T) serviceMap.get(interfaceClass);
    }
}
